package com.sky.service.User;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.user.UserLoginDTO;
import com.sky.entity.Category;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetMeal;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.exception.UserNotDishException;
import com.sky.mapper.FlavorsMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.utils.HttpClientUtils;
import com.sky.vo.UserDishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 褚金龙
 * @Date 2024/9/17 10:42
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService{
  @Autowired
    private UserMapper userMapper;
  @Autowired
  private FlavorsMapper flavorsMapper;
    private static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
     @Autowired
     private WeChatProperties weChatProperties;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        // 判断openid是否为空，如果为空表示登录异常，抛出业务异常
        if(openid==null){

           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前用户是否为新用户,使用openid在用户表查找有相同的没
        User user = userMapper.getByOpenid(openid);
        if(user==null){
            //如果是新用户自动完成注册

          user=  User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
           //注册
          userMapper.insert(user);
        }
            //返回这个用户对象


        return user;
    }



    /**
     * 调用微信接口服务获取openid
     * @param code
     * @return
     */
    public String getOpenid(String code){
        // 调用微信接口服务，获得当前微信用户的openid
        Map<String, String> paramMap=new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String json = HttpClientUtils.doGet(WX_LOGIN, paramMap);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }



    /**
     * 根据类型查询分类表
     *
     * @return
     */
    @Override
    public List<Category> categoryList(Integer type) {
        List<Category> categories = userMapper.categoryList(type);
        return categories;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<UserDishVO> dishList(Integer categoryId) {
        List<Long>ids=new  ArrayList<>();

        //查询所有菜品


        List<UserDishVO> dishes= userMapper.dishList(categoryId);
        if(dishes.size()==0){
          throw new UserNotDishException(MessageConstant.CATEGORY_NOT_DISH);
        }






        //查询所有对应口味

            for (UserDishVO dish : dishes) {
                ids.add(dish.getId());
            }



        List<DishFlavor> flavors= flavorsMapper.allgetByflavors(ids);
        //把口味赋值给对应的dishes
        for (int i = 0; i < flavors.size(); i++) {
            for (int j = 0; j < dishes.size(); j++) {
                if(flavors.get(i).getDishId()==dishes.get(j).getId()){

                    dishes.get(j).setFlavors(flavors.get(i));
                }
            }


        }

        return dishes;
    }

    @Override
    public List<SetMeal> setMealList(Integer categoryId) {
        List<SetMeal> setMeals= userMapper.setMaelList(categoryId);
        return setMeals;
    }


}
